package com.cdwm.mrp.common.tools;


import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/5
 */
@Slf4j
public abstract class JWTUtil {
    /**
     * 令牌密钥
     */
    private static final String SECRET = "zysheep";
    /**
     * 令牌密钥前缀
     */
    private static final String TOKEN_PREFIX = "Bearer ";
    /**
     * 令牌有效期（毫秒）
     */
    private static final long EXPIRATION_TIME = 24*60*60*1000;


    public static String createToken() {
        return createToken(null);
    }

    /**
     * 创建token
     * @param param
     * @return
     */
    public static String createToken(Map<String,Object> param) {

        Map<String,Object> tempParam = ObjectUtils.isEmpty(param) ? new HashMap<>() : param;

        String jwt =  Jwts.builder()
                .setClaims(tempParam)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .compact();
        return TOKEN_PREFIX + jwt;
    }


    /**
     * 解析token
     * @param token
     * @return
     */
    public static Map<String,Object> parseToken(String token) {

        Map<String,Object> map = new HashMap<>();

        if(ObjectUtils.isEmpty(token)) {
            map.put("ERR_CODE",400100);
            map.put("ERR_MSG", "令牌不存在！");
            return map;
        }

        try {
            Map<String,Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();

            return body;
        } catch (SignatureException | MalformedJwtException e) {
            log.error("令牌错误!",e);
            map.put("ERR_CODE",400200);
            map.put("ERR_MSG", "令牌错误!");
            return map;
        } catch (ExpiredJwtException e) {
            log.error("令牌已过期!",e);
            map.put("ERR_CODE",400200);
            map.put("ERR_MSG", "令牌已过期!");
            return map;
        }
    }
}

